<?php
class connect{
	private static $instance;
	private $link = null;
	private $data = null;
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new connect();
		}
		return self::$instance;
	}
	public function connect($pconnect = 0,$host=DATABASE_CONNECT_HOST,$user=DATABASE_CONNECT_USER,$password=DATABASE_CONNECT_PASS,$dbname = DATABASE_NAME,$dbcharset="utf8")
	{
		$connect = empty($pconnect) ? "mysql_connect" : "mysql_pconnect";
		$this->link = @$connect($host,$user,$password) or exit("Could not connect: " . mysql_error());
		$version = mysql_get_server_info($this->link);
		if($version > '4.1') {
			if($dbcharset) {
				mysql_query("SET character_set_connection=".$dbcharset.", character_set_results=".$dbcharset.", character_set_client=binary", $this->link);
			}
			if($version > '5.0.1') {
				mysql_query("SET sql_mode=''", $this->link);
			}
		}
		if(!empty($dbname)){
			mysql_select_db($dbname, $this->link) or exit(mysql_error());
		}
	}
	public function query($sql,$page=-1){
		if($page!=-1){
			$data = mysql_query($sql,$this->link );
			$count = mysql_num_rows($data);
			$pagecount = ceil($count/ONEPAGE_SIZE);
			$page =($page>=$pagecount)?$pagecount:$page;
			$page =($page<=1)?1:$page;
			$sql .=" LIMIT ".($page-1)*ONEPAGE_SIZE.",".ONEPAGE_SIZE;
		}
		$this->data = mysql_query($sql,$this->link ) or exit("Invalid query: " . mysql_error());
	}

	public function GetCount($sql){
		$data = mysql_query($sql,$this->link );
		return mysql_num_rows($data);
	}
	public function Result($result_type = MYSQL_ASSOC){
		$array = null;
		$row = 0;
		while ($rs= mysql_fetch_array($this->data,$result_type)) {
			$array[$row]=$rs;
			$row++;
		}
		mysql_free_result($this->data);
		return $array;
	}

	public function insert_id() {
		return ($id = mysql_insert_id($this->link)) >= 0 ? $id : mysql_result($this->query("SELECT last_insert_id()"), 0);
	}

	public function close() {
		return mysql_close($this->link);
	}
	function __destruct(){
		return mysql_close($this->link);
	}
}